package com.cyandpos.pad.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cyandpos.pad.R;
import com.cyandpos.pad.common.commondata.BaseResponse;
import com.cyandpos.pad.common.commondata.Constant;
import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.common.commondata.SktConfigIdCrmConstant;
import com.cyandpos.pad.common.netmanager.PosHttpManager;
import com.cyandpos.pad.common.swipemanager.SwipeCardCommon;
import com.cyandpos.pad.http.OkHttpUtils;
import com.cyandpos.pad.netdata.Res_MoneyBuyPro;
import com.cyandpos.pad.posdata.BackUploadResult;
import com.cyandpos.pad.posdata.CardCouponItem;
import com.cyandpos.pad.posdata.CodeCoupon;
import com.cyandpos.pad.posdata.Coupon;
import com.cyandpos.pad.posdata.CouponPayBack;
import com.cyandpos.pad.posdata.Goods;
import com.cyandpos.pad.posdata.Member;
import com.cyandpos.pad.posdata.MoneyBuyCentData;
import com.cyandpos.pad.posdata.OfferCoupon;
import com.cyandpos.pad.posdata.Payment;
import com.cyandpos.pad.posdata.Person;
import com.cyandpos.pad.posdata.PrepareRefundData;
import com.cyandpos.pad.posdata.ProMoneyPayment;
import com.cyandpos.pad.posdata.QueryMemberReq;
import com.cyandpos.pad.posdata.SubTicketItem;
import com.cyandpos.pad.posdata.TicketInfo;
import com.cyandpos.pad.refund.TimeThread;
import com.cyandpos.pad.refund.adapter.RefundGoodsAdapter;
import com.cyandpos.pad.refund.adapter.RefundPaymentAdapter;
import com.cyandpos.pad.refund.adapter.ShowCouponAdapter;
import com.cyandpos.pad.refund.contract.UploadRefundContract;
import com.cyandpos.pad.refund.presenter.UploadRefundPresenterImpl;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.MoneyUtils;
import com.cyandpos.pad.utils.PayUtil;
import com.cyandpos.pad.utils.ToastUtils;
import com.google.gson.JsonObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class RefundActivity extends BaseActivity implements UploadRefundContract.View, SwipeCardCommon.DoAfterSwipeCard{
    @BindView(R.id.tv_main_title_version)
    TextView mTv_title_versin;
    @BindView(R.id.tv_main_title_cashier)
    TextView mTv_title_cashier;
    @BindView(R.id.tv_main_title_sktno)
    TextView mTv_title_sktno;
    @BindView(R.id.tv_main_title_orderno)
    TextView mTv_title_orderno;
    @BindView(R.id.tv_main_title_currentTime)
    public TextView tvMainTitleCurrentTime;
    @BindView(R.id.iv_main_project_logo)
    ImageView mIv_project_logo;
    @BindView(R.id.ktno)
    TextView mTvOldsktno;
    @BindView(R.id.btn_main_exit_system)
    Button mbtExit;
    @BindView(R.id.time)
    TextView mTvTime;
    @BindView(R.id.ticket)
    TextView mTvOldticketno;
    @BindView(R.id.syy)
    TextView mTvOldsyy;
    @BindView(R.id.tv_main_goods_totalNum)
    TextView mTv_goods_totalNum;
    @BindView(R.id.tv_shold_refund)
    TextView mTvSholdRefund;
    @BindView(R.id.lv_refund_goodList)
    RecyclerView mRvRefunds;
    @BindView(R.id.lv_main_select_pament)
    RecyclerView mLv_pament;

    private final MyHandler handler = new MyHandler(this);

    private String old_sktno,old_orderNo,managerNo;
    public TicketInfo ticket;
    private ProgressDialog dialog;
    private RefundGoodsAdapter mRefundsAdapter;
    private RefundPaymentAdapter mRefundsPaymentAdapter;
    private ArrayList<Goods> goodsList;
    public UploadRefundContract.Presenter mPresenter;
    private List<OfferCoupon> mOfferBacks;
    private List<CardCouponItem> mCouponBack;
    private List<CodeCoupon> mCodedCouponBack;
    private TicketInfo mTicketInfo;
    private BackUploadResult mUploadResult;
    private boolean isAllOrder;
    private boolean isNeedBuyCent = false;
    private int buyCentMoneyPay = 0;

    @Override
    protected void initData() {
        dialog = new ProgressDialog(RefundActivity.this);
        dialog.setCancelable(false);
        dialog.setMessage("退货上传商品 ....");
        goodsList=new ArrayList<>();
        old_sktno=getIntent().getStringExtra("old_sktno");
        old_orderNo=getIntent().getStringExtra("old_orderNo");
        managerNo=getIntent().getStringExtra("managerNo");
        isAllOrder = getIntent().getBooleanExtra("isAllOrder",false);
        ticket=(TicketInfo)getIntent().getSerializableExtra("TicketInfo");
        mTv_title_versin.setText(CommonUtils.getCurrentVersionName(this));
        mTv_title_cashier.setText(ErpCommonData.loadConfig.getCashierCode());
        mTv_title_sktno.setText(ErpCommonData.sktno);
        mTv_title_orderno.setText(ticket.getOrderNo());

        if (ticket!=null){
            showOldTicekinfo();
        }
        mPresenter = new UploadRefundPresenterImpl(this, this);
        TimeThread timeThread = new TimeThread(handler);
        timeThread.setDaemon(true);//守护线程
        timeThread.start();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_refund;
    }

    public void showOldTicekinfo() {
        mTvOldsktno.setText("原收款台:" + old_sktno);
        mTvOldticketno.setText("原小票号:" + old_orderNo);
        mTvOldsyy.setText("原收款员:" + ticket.getCasherInfo().getPersonName());
        mTvTime.setText("原交易时间:" + ticket.getOrderTime());

        for (SubTicketItem item:ticket.getSubTickets()){
            for (Goods good:item.getGoodsList()){
                good.setRefundCount(String.valueOf(Integer.valueOf(good.getSaleCount())-Integer.valueOf(good.getHasedRefundCount())));
                goodsList.add(good);
            }
        }
        upDateShowRefund(goodsList);

//        if (ticket.getMemberInfo() != null) {
//            if (ticket.getMemberInfo().getMemberCardNo()!=null){
//                mTvMemberInfo.setText(ticket.getMemberInfo().getMemberCardNo());
//            }else {
//                mTvMemberInfo.setText("无");
//            }
//            if (ticket.getMemberInfo().getMemberName() != null) {
//                mTvMemberMC.setText(ticket.getMemberInfo().getMemberName());
//            } else {
//                mTvMemberMC.setText("");
//            }
//        }

        if (ticket.getSubTickets() != null && ticket.getSubTickets().size() > 0) {
            if (goodsList!=null && goodsList.size()>0){
                mRefundsAdapter = new RefundGoodsAdapter(this, goodsList,isAllOrder);
                mRvRefunds.setLayoutManager(new LinearLayoutManager(this));
                mRvRefunds.setAdapter(mRefundsAdapter);
            }
        } else {
            ToastUtils.show("获取原交易信息出错");
        }

        if (ticket.getPayList() != null && ticket.getPayList().size() >0){
            mRefundsPaymentAdapter = new RefundPaymentAdapter(this, ticket.getPayList());
            mLv_pament.setLayoutManager(new LinearLayoutManager(this));
            mLv_pament.setAdapter(mRefundsPaymentAdapter);
        }
    }
    public void upDateShowRefund( ArrayList<Goods> goodsList) {
        int shouldRefund = 0;
        int count = 0;
        for (Goods good : goodsList) {
            double ZKFT=Double.valueOf(good.getRefundCount()) / Double.valueOf(good.getSaleCount());
            String money1 = MoneyUtils.getMultiply(good.getRefundCount(), good.getPrice()).toString();
            String money2 = MoneyUtils.getMultiply(good.getDiscount(), ZKFT + "").toString();
            shouldRefund+=MoneyUtils.getMoneyInt(MoneyUtils.getSubtractMoney(money1,money2).toString());
            count += Double.valueOf(good.getRefundCount());
        }
        mTvSholdRefund.setText(MoneyUtils.getMoneyStr(shouldRefund));
        mTv_goods_totalNum.setText("   "+ count );
    }

    @Override
    public void showProgress() {
        dialog.setMessage("退货上传商品.....");
        dialog.show();
    }

    @Override
    public void dismissDialog() {
        if (dialog.isShowing()) {
            dialog.cancel();
        }
    }

    @Override
    public void showErrMessage(String msg) {
        ToastUtils.show(msg);
    }

    @Override
    public void onSucess(BackUploadResult result) {
        mUploadResult = result;
        mTicketInfo = new TicketInfo();
        mTicketInfo.setServerBillId(result.getServerBillId());
        mTicketInfo.setJlbh(result.getJlbh());
        mTicketInfo.setSktno(ErpCommonData.sktno);
        mTicketInfo.setOrderNo(result.getOrderNo());
        mTicketInfo.setOldOrderNo(old_orderNo);
        mTicketInfo.setStoreCode(result.getStoreCode());
        mTicketInfo.setTotalCount(MoneyUtils.getMabMoneyString(result.getTotalCount()));
        mTicketInfo.setTotalAmount(MoneyUtils.getMabMoneyString(result.getTotalAmount()));
        mTicketInfo.setTotalDiscount(MoneyUtils.getMabMoneyString(result.getTotalDiscount()));
        mTicketInfo.setDecMoney(MoneyUtils.getMabMoneyString(result.getDecMoney()));
        mTicketInfo.setDecPreferentialMoney(MoneyUtils.getMabMoneyString(result.getDecPreferentialMoney()));
        Person person = new Person();
        person.setPersonCode(ErpCommonData.loadConfig.getCashierCode());
        person.setPersonId(Integer.valueOf(ErpCommonData.loadConfig.getCashierId()));
        person.setPersonName(ErpCommonData.loadConfig.getCashierName());
        person.setPersonDeptCode(ErpCommonData.loadConfig.getCashierDeptCode());
        person.setPersonDeptId(Integer.valueOf(ErpCommonData.loadConfig.getCashierDeptId()));
        person.setPersonDeptName(ErpCommonData.loadConfig.getCashierDeptName());
        person.setShopId(0);
        mTicketInfo.setCasherInfo(person);
        mTicketInfo.setMemberInfo(ticket.getMemberInfo());

        mTicketInfo.getSubTickets().clear();

        for (SubTicketItem item:ticket.getSubTickets()){
            mTicketInfo.getSubTickets().add(item);
        }
        //判断是否需要钱买分
        if(result.isNeedBuyCent() && ticket.getMemberInfo().getMemberCardId()>0
                && result.getNeedBuyCent()!=null &&  Math.abs(Double.parseDouble(result.getNeedBuyCent()))>0
                && result.getBuyMoney()!=null && Math.abs(Double.parseDouble(result.getBuyMoney()))>0 ){//需要钱买分
            showMoneyBuyCentPaymentDialog(result.getNeedBuyCent(),result.getBuyMoney(),result.getCzkBalance());
        }else{
            if(result.getOfferBackCouponList()!=null && result.getOfferBackCouponList().size()>0){
                mOfferBacks = result.getOfferBackCouponList();
                ArrayList<Coupon> list = new ArrayList<>();
                for (OfferCoupon offerBack : mOfferBacks) {
                    Coupon item = new Coupon();
                    item.setCouponTypeName(offerBack.getCouponTypeName());
                    item.setAvailableAmount(offerBack.getOfferMoney()+"");
                    list.add(item);
                }
                ticket.setOfferCouponList(mOfferBacks);
                checkforCompus(mUploadResult);
            }else {
                checkforCompus(result);
            }
        }
    }

    @Override
    public PrepareRefundData getTicketInfo() {
        if (goodsList!=null && goodsList.size()>0){
            PrepareRefundData backUploadReq = new PrepareRefundData();
            backUploadReq.setDdlx("1");
            backUploadReq.setDdly("1");
            backUploadReq.setStoreCode(ErpCommonData.storeCode);
            backUploadReq.setSktno(ErpCommonData.sktno);
            backUploadReq.setOperatorCode(ticket.getCasherInfo().getPersonCode());
            backUploadReq.setOldOrderNo(ticket.getOrderNo());
            backUploadReq.setGoodsList(handBackGoods(goodsList));
            return backUploadReq;
        }
        return null;
    }


    @Override
    public void onGetVIPsuccess(Member member) {
        for (CardCouponItem item:mCouponBack){
            item.setCardId(member.getMemberCardId());
            item.setCardCode(member.getMemberCardNo());
        }
        ticket.getCardCouponList().clear();
        ticket.getCardCouponList().addAll(mCouponBack);
        ErpCommonData.ticketInfo = mTicketInfo;
        ErpCommonData.oldTicket=ticket;
        Bundle bundle = new Bundle();
        bundle.putInt("SaleType", 1);
        go2Activity(PayActivity.class, bundle);
    }

    private static ArrayList<Goods> handBackGoods(ArrayList<Goods> goodsList){
        ArrayList<Goods> backGoods = new ArrayList<>();
        for (Goods goods :  goodsList){
            if (Integer.valueOf(goods.getRefundCount())>0){
                Goods backUpLoadGoods = new Goods();
                backUpLoadGoods.setInx(goods.getInx());
                backUpLoadGoods.setGoodsGuid(goods.getGoodsGuid());
                backUpLoadGoods.setBarCode(goods.getBarCode());
                backUpLoadGoods.setCode(goods.getCode());
                backUpLoadGoods.setName(goods.getName());
                backUpLoadGoods.setId(goods.getId()+"");
                backUpLoadGoods.setUnit(goods.getUnit());
                backUpLoadGoods.setPrice(goods.getPrice());
                backUpLoadGoods.setSaleCount("-"+goods.getRefundCount());
                String saleStr = MoneyUtils.getMoneyStr(Math.abs(Double.parseDouble(goods.getRefundCount())*
                        ( MoneyUtils.getMoneyInt(goods.getPrice()))));//-(MoneyUtils.getMoneyInt(goods.getDiscount())/Integer.valueOf(goods.getSaleCount()))- MoneyUtils.getMoneyInt(goods.getPreferentialMoney())
                backUpLoadGoods.setSaleMoney("-"+saleStr);
//                String disStr = MoneyUtils.getMoneyStr( Math.abs(Integer.valueOf(goods.getRefundCount())*(MoneyUtils.getMoneyInt(goods.getDiscount())/Integer.valueOf(goods.getSaleCount())
//                        -MoneyUtils.getMoneyInt(goods.getPreferentialMoney()))));
                backUpLoadGoods.setDiscount("-" + goods.getDiscount());
                backUpLoadGoods.setPreferentialMoney("-"+goods.getPreferentialMoney());
                backUpLoadGoods.setTicktInx(goods.getTicktInx()+"");
                backUpLoadGoods.setTicktGoodsInx(goods.getTicktGoodsInx()+"");
                backGoods.add(backUpLoadGoods);
            }

        }
        return backGoods;
    }

    //选择买分的付款方式
    private void showMoneyBuyCentPaymentDialog(final String needBuyCent,final String buyCentMoney,final String czkBlance) {//final R_QueryBuyCentNeedMoney resBuy
        View view = View.inflate(RefundActivity.this, R.layout.dialog_money_buy_cent, null);
        TextView tvTitle = (TextView) view.findViewById(R.id.tv_dialog_title_name);

        TextView tv_totalCent= (TextView) view.findViewById(R.id.tv_money_buy_cent_how);
        TextView tv_money= (TextView) view.findViewById(R.id.tv_money_buy_cent_money);
        TextView payName = (TextView) view.findViewById(R.id.tv_buyCent_payName);
        final TextView tvPayMoney  = (TextView) view.findViewById(R.id.tv_money_buy_cent_cashMoney);

        Button btn_ok = (Button) view.findViewById(R.id.btn__money_buy_cent_ok);
        Button btn_cancel = (Button) view.findViewById(R.id.btn__money_buy_cent_cancel);

        tvTitle.setText("积分不足钱买分详情");
        tv_totalCent.setText(Math.abs(Double.parseDouble(needBuyCent))+"");
        tv_money.setText(buyCentMoney+" 元");
        String qmfPayName ="现金";
        for(Payment p :ErpCommonData.loadConfig.getPayList()){
            if(p.getPayType() == Payment.SKFS_QMF){
                qmfPayName =p.getPayName();
                break;
            }
        }
        payName.setText(qmfPayName);
        tvPayMoney.setText(buyCentMoney+" 元");
        AlertDialog.Builder builder = new AlertDialog.Builder(RefundActivity.this);
        final AlertDialog dialog = builder.setView(view).setCancelable(false).show();
        final WindowManager manager = getWindowManager();
        Display display = manager.getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.getWindow().setLayout(width, height/2);

        //关闭按钮
        tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                reqProcMoneyToCent(buyCentMoney,needBuyCent);
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {//取消
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }

    private void reqProcMoneyToCent(final String buyCentMoney, String needBuyCent) {
        MoneyBuyCentData data = new MoneyBuyCentData();
        data.setVipId(ticket.getMemberInfo().getMemberCardId());
        data.setVipCode(ticket.getMemberInfo().getMemberCardNo());
        data.setNeedBuyCent(Math.abs(Double.parseDouble(needBuyCent))+"");
        data.setSktno(ErpCommonData.sktno);
        data.setCashMoney(MoneyUtils.getMoneyInt(buyCentMoney +""));
        data.setCzkMoney(0);
        data.setYhqMoney(0);
        data.setPersonCode(ErpCommonData.loadConfig.getCashierCode());
        data.setPersonId(Integer.parseInt(ErpCommonData.loadConfig.getCashierId()));
        data.setPersonName(ErpCommonData.loadConfig.getCashierName());
        data.setJlbh(ticket.getJlbh());
        data.setOldSktno(ErpCommonData.sktno);
        data.setOldJlbh(ticket.getJlbh());
        ProMoneyPayment p = new ProMoneyPayment();
        for(Payment pI: ErpCommonData.loadConfig.getPayList()){
            if(pI.getPayType() == Payment.SKFS_QMF){
                p.setPayId(pI.getPayCode());
                p.setPayMoney(MoneyUtils.getMoneyInt(buyCentMoney+""));
            }
        }
        data.getPayList().add(p);
        PosHttpManager.procMoneyToCent(data, new OkHttpUtils.ResultCallback() {
            @Override
            public void onSuccess(JsonObject response) {
                BaseResponse<Res_MoneyBuyPro> baseResponse = BaseResponse.fromJson(response.toString(), Res_MoneyBuyPro.class);
                if(baseResponse.getCode().equals("0")){
                    isNeedBuyCent = true;
                    buyCentMoneyPay = MoneyUtils.getMoneyInt(buyCentMoney+"");
                    //重新调用退货上传商品
                    mPresenter.upLoadBackGoods();

//                    ErpCommonData.ticketInfo = mTicketInfo;
//                    ErpCommonData.oldTicket=ticket;
//                    Bundle bundle = new Bundle();
//                    bundle.putInt("SaleType", 1);
//                    bundle.putBoolean("isNeedBuyCent", true);
//                    bundle.putInt("buyCentMoney", MoneyUtils.getMoneyInt(buyCentMoney+""));
//                    go2Activity(PayActivity.class, bundle);
                }else{
                    ToastUtils.showMsg("钱买分核销失败！");
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtils.showMsg("钱买分核销失败！");
            }
        });
    }

    /**
     * 扣返券信息
     *
     */
    private void showOfferBacksDialog(ArrayList<Coupon> list,final int couponFlag) {
        View view = View.inflate(this, R.layout.dialog_yhj, null);
        TextView title = (TextView) view.findViewById(R.id.tv_kq_title);
        RecyclerView rv_coupon = (RecyclerView) view.findViewById(R.id.rv_coupon_info);
        final Button btnOkButton = (Button) view.findViewById(R.id.btn_dialog_coupon_ok);
        final Button btnCancelButton = (Button) view.findViewById(R.id.btn_dialog_coupon_cancel);
        if(couponFlag == Constant.COUPON_SHOW_RETURN_OLDTRACE_OFFER_BACK_COUPON){
            title.setText("扣返券信息");
        }else if(couponFlag == Constant.COUPON_SHOW_RETURN_OLDTRACE_PAY_COUPON){
            title.setText("退用券信息");
        }

        ShowCouponAdapter adapter = new ShowCouponAdapter(RefundActivity.this, list);
        rv_coupon.setLayoutManager(new LinearLayoutManager(this));
        rv_coupon.setAdapter(adapter);

        final AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(view).create();
        dialog.setCancelable(false);
        dialog.show();
        btnOkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if(couponFlag == Constant.COUPON_SHOW_RETURN_OLDTRACE_OFFER_BACK_COUPON){
                    ticket.setOfferCouponList(mOfferBacks);
                    checkforCompus(mUploadResult);
                }else if(couponFlag == Constant.COUPON_SHOW_RETURN_OLDTRACE_PAY_COUPON){
                    if(mCouponBack!=null && mCouponBack.size()>0){//卡券
                        PayUtil.showQueryMemberDialog(RefundActivity.this,Constant.MEMBER_IDENTIFYING_REFUND);
                    }else if (mCodedCouponBack!=null && mCodedCouponBack.size()>0){//编码券
                        ticket.getCodedCouponList().clear();
                        ticket.getCardCouponList().clear();
                        ticket.getCodedCouponList().addAll(mCodedCouponBack);
                        ticket.getCardCouponList().addAll(mCouponBack);
                        ErpCommonData.ticketInfo = mTicketInfo;
                        ErpCommonData.oldTicket=ticket;
                        Bundle bundle = new Bundle();
                        bundle.putInt("SaleType", 1);
                        bundle.putBoolean("isNeedBuyCent", isNeedBuyCent);
                        bundle.putInt("buyCentMoney",buyCentMoneyPay);
                        go2Activity(PayActivity.class, bundle);
                    }else {
                        PayUtil.showQueryMemberDialog(RefundActivity.this,Constant.MEMBER_IDENTIFYING_REFUND);
                    }


                    //PayUtil.showQueryMemberDialog(RefundActivity.this,Constant.MEMBER_IDENTIFYING_REFUND);
                }
            }
        });

        btnCancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if(couponFlag == Constant.COUPON_SHOW_RETURN_OLDTRACE_OFFER_BACK_COUPON){//返券
                    checkforCompus(mUploadResult);
                }else if(couponFlag == Constant.COUPON_SHOW_RETURN_OLDTRACE_PAY_COUPON){//用券
                    ticket.getCodedCouponList().clear();
                    ticket.getCardCouponList().clear();
                    ticket.getCodedCouponList().addAll(mCodedCouponBack);
                    ticket.getCardCouponList().addAll(mCouponBack);
                    ErpCommonData.ticketInfo = mTicketInfo;
                    ErpCommonData.oldTicket=ticket;
                    Bundle bundle = new Bundle();
                    bundle.putInt("SaleType", 1);
                    bundle.putBoolean("isNeedBuyCent", isNeedBuyCent);
                    bundle.putInt("buyCentMoney",buyCentMoneyPay);
                    go2Activity(PayActivity.class, bundle);


//                    if(isNeedBuyCent && ticket.getMemberInfo().getMemberCardId()>0
//                            && mUploadResult.getNeedBuyCent()!=null &&  Math.abs(Double.parseDouble(mUploadResult.getNeedBuyCent()))>0
//                            && mUploadResult.getBuyMoney()!=null && Math.abs(Double.parseDouble(mUploadResult.getBuyMoney()))>0 ){//需要钱买分
//                        showMoneyBuyCentPaymentDialog(mUploadResult.getNeedBuyCent(),mUploadResult.getBuyMoney(),mUploadResult.getCzkBalance());
//                    }else{
//
//                    }
                }
            }
        });

    }

    private void checkforCompus(BackUploadResult result) {
        if (result.getCouponPaybackList() != null && result.getCouponPaybackList().size() > 0) {
            mCouponBack = new ArrayList<>();//卡券
            mCodedCouponBack = new ArrayList<>();//编码券
            for (CouponPayBack couponPayback : result.getCouponPaybackList()) {
                boolean isCodedCoupon = false;
                CardCouponItem yhqItem=new CardCouponItem();
                CodeCoupon codedItem=new CodeCoupon();
                for (Payment payment : ErpCommonData.loadConfig.getPayList()) {
                    if (payment.getYhqId() == couponPayback.getCouponType()) {
                        yhqItem.setCouponTypeName(payment.getPayName());
                        if(payment.getIsCoded()==1)//编码券
                            isCodedCoupon = true;
                    }
                }
                if(isCodedCoupon){
                    codedItem.setUsedMoney(Math.abs(MoneyUtils.getMoneyInt(couponPayback.getPayMoney()+"")));
                    codedItem.setCouponType(couponPayback.getCouponType());
                    codedItem.setCodeCouponName(couponPayback.getCouponTypeName());
                    mCodedCouponBack.add(codedItem);

                }
                else{
                    yhqItem.setUsedMoney(Math.abs(MoneyUtils.getMoneyInt(couponPayback.getPayMoney()+"")));
                    yhqItem.setCouponType(couponPayback.getCouponType());
                    mCouponBack.add(yhqItem);
                }
            }
            ArrayList<Coupon> list = new ArrayList<>();
            for (CardCouponItem yhqItem : mCouponBack) {
                Coupon item = new Coupon();
                item.setCouponTypeName(yhqItem.getCouponTypeName());
                item.setAvailableAmount(MoneyUtils.getMoneyStr(Math.abs(yhqItem.getUsedMoney())));
                list.add(item);
            }
            for (CodeCoupon codedItem : mCodedCouponBack) {
                Coupon item = new Coupon();
                item.setCouponTypeName(codedItem.getCodeCouponName());
                item.setAvailableAmount(MoneyUtils.getMoneyStr(Math.abs(codedItem.getUsedMoney())));
                list.add(item);
            }
            showOfferBacksDialog(list,Constant.COUPON_SHOW_RETURN_OLDTRACE_PAY_COUPON);
        } else {
            ErpCommonData.ticketInfo = mTicketInfo;
            ErpCommonData.oldTicket=ticket;
            Bundle bundle = new Bundle();
            bundle.putInt("SaleType", 1);
            bundle.putBoolean("isNeedBuyCent", isNeedBuyCent);
            bundle.putInt("buyCentMoney",buyCentMoneyPay);
            go2Activity(PayActivity.class, bundle);

//            if(isNeedBuyCent && ticket.getMemberInfo().getMemberCardId()>0
//                    && result.getNeedBuyCent()!=null &&  Math.abs(Double.parseDouble(result.getNeedBuyCent()))>0
//                    && result.getBuyMoney()!=null && Math.abs(Double.parseDouble(result.getBuyMoney()))>0 ){//需要钱买分
//                showMoneyBuyCentPaymentDialog(result.getNeedBuyCent(),result.getBuyMoney(),result.getCzkBalance());
//            }else{
//
//            }

        }
    }

    @Override
    public void doAfterSwipeCard(boolean isSuccess, String result, int handId) {
        if (isSuccess) {
            switch (handId){
                case Constant.REFUND_SWIPECARD_HANDLEID:{
                    queryMemberReturn(result,SktConfigIdCrmConstant.SKT_CONFIG_MEMBER_TYPE_SWIPE+"");
                }
                break;
                default:
                    break;
            }

        } else {
            ToastUtils.showMsg( "读取内容失败！请重试",0);
        }
    }


    public static class MyHandler extends Handler {
        private final WeakReference<RefundActivity> mActivity;

        public MyHandler(RefundActivity activity) {
            this.mActivity = new WeakReference<RefundActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            RefundActivity mainActivity = mActivity.get();
            if (mainActivity == null) {
                return;
            }
            switch (msg.what) {
                case Constant.MAIN_UPDATE_CURRENT_TIME_HANDLEID: {
                    String time = msg.getData().getString("time");
                    mainActivity.tvMainTitleCurrentTime.setText(time);
                    break;
                }
                default:
                    break;
            }
        }

    }
    @OnClick({ R.id.btn_main_exit_system,R.id.btn_sure_keyboard})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_exit_system:
                ErpCommonData.ticketInfo = new TicketInfo();
                finish();
                break;
            case R.id.btn_sure_keyboard:
                int tempRefundCount = 0;
                for(Goods g:goodsList){
                    tempRefundCount+=Integer.valueOf(g.getRefundCount());
                }
                if(tempRefundCount ==0){
                    ToastUtils.showMsg("退货商品数量不可为0！");
                    return;
                }
                mPresenter.upLoadBackGoods();
                break;
        }
    }
    /**
     * 退货查询会员
     * @param result
     */
    public void queryMemberReturn(String result,String type) {
        QueryMemberReq memberReq = new QueryMemberReq();
        memberReq.setCondType(type);
        memberReq.setCardNo(result);
        memberReq.setOrderNo(mTicketInfo.getOrderNo());
        memberReq.setStoreCode(ErpCommonData.storeCode);
        mPresenter.getVipInfo(memberReq);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case Constant.RETURN_SCAN_HANDLEID:{//退货会员扫码
                String content = data.getStringExtra("Code");
                if ("".equals(content)) {
                    Toast.makeText(this, "扫码结果为空,请重试！", Toast.LENGTH_LONG).show();
                }else{
                    queryMemberReturn(content, SktConfigIdCrmConstant.SKT_CONFIG_MEMBER_TYPE_SCAN+"");
                }
            }
            break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
